package com.meicet.adapter.base

import kotlinx.coroutines.*
@Deprecated("过期了")
class TaskLife(private val oneSingle: Boolean = false) {
    private val lifeList = HashMap<Int, DisposableLife>()
    private val coroutine by lazy { MainScope() }
    private val coroutineIO by lazy { CoroutineScope(Dispatchers.IO) }
    private var isInitCoroutine = false
    private var isInitCoroutineIO = false
    fun coroutine(): CoroutineScope {
        isInitCoroutine = true
        return coroutine
    }
    fun coroutineIO(): CoroutineScope {
        isInitCoroutineIO = true
        return coroutineIO
    }

    fun onDestroy() {
        if (isInitCoroutine && coroutine.isActive) {
            coroutine.cancel()
        }
        if (isInitCoroutineIO && coroutineIO.isActive) {
            coroutineIO.cancel()
        }
        if (lifeList.isEmpty()) return
        synchronized(TaskLife::class.java) {
            lifeList.values.forEach {
                it.onDestroy()
            }
            lifeList.clear()
        }
    }

    fun removeTask(hash: Int) {
        lifeList.remove(hash)
//        _i("减 TaskLife $hash")
    }

    fun addTask(task: DisposableLife, hash: Int) {
        //        _i("加 TaskLife $hash")
        if (oneSingle) {
            onDestroy()
        }
        lifeList[hash] = task
    }
}
